import streamlit as st
from audiorecorder import audiorecorder
import os
from vosk import Model, KaldiRecognizer
import json
import wave

# 加载Vosk模型
model_path = "zhongwen"  # 确保路径正确
if not os.path.exists(model_path):
    st.error(f"模型路径 {model_path} 不存在，请下载并放置正确路径")
    st.stop()

model = Model(model_path)

# Streamlit界面
st.title("实时语音识别客户端")
st.write("点击下方按钮开始录音，录音结束后会自动转换为文字。")

# 使用 audiorecorder 录制音频
audio = audiorecorder("开始录音", "结束录音")

if len(audio) > 0:
    # 保存录音为 WAV 文件
    wav_file = os.path.abspath("output.wav")  # 使用绝对路径
    with open(wav_file, "wb") as f:
        print("1")
        f.write(audio.tobytes())

    st.audio(wav_file, format="audio/wav")

    # 提供下载录音的链接
    with open(wav_file, "rb") as f:
        st.download_button("下载录音", f, file_name="recording.wav")

    # 将录音转换为文字
    recognizer = KaldiRecognizer(model, 16000)

    with wave.open(wav_file, "rb") as wf:
        if wf.getnchannels() != 1 or wf.getsampwidth() != 2 or wf.getframerate() != 16000:
            st.error("音频格式不正确，请确保音频为单声道、16位、16kHz采样率")
        else:
            while True:
                data = wf.readframes(4000)
                if len(data) == 0:
                    break
                if recognizer.AcceptWaveform(data):
                    result = recognizer.Result()
                    result_text = json.loads(result)['text']
                    st.write(f"识别结果: {result_text}")

            # 获取最终结果
            final_result = recognizer.FinalResult()
            final_text = json.loads(final_result)['text']
            st.write(f"最终识别结果: {final_text}")